<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			body {
				/*background: gray;*/
				margin: 0;
				padding: 0;
			}
			.main {
				margin: 20px auto;
				text-align: center;
			}
			#canvas {
				background: #ffffff;
				margin: 0 auto;
				border-radius: 10px;
			}
			
			.img-box {
				background: #fff;
				border-bottom: 1px solid #999999;
				width: 400px;
				margin: 0 auto;
				text-align: left;
			}
			
			.img-box img {
				width: 50px;
				height: 50px;
			}
			.canvas-box {
				display: inline-block;
				background: gray;
				padding: 10px;
			}
		</style>
	</head>

	<body>
		<div class="main">
			<div class="canvas-box">
				<canvas id="canvas" width="300" height="300"></canvas>
			</div>
			<p>
				<button onclick="exportImg();">确定</button>
				<button onclick="clearCanvas();">清空画布</button>
				<button onclick="clearImg();">清除文字</button>
			</p>
			<div id="imgBox" class="img-box">

			</div>
		</div>

	</body>

</html>

<script type="text/javascript">
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	var imgBox = document.getElementById('imgBox');
	var isPress = false;
	canvas.onmousedown = function (ev) {
		isPress = true;
		ev = ev || event;
		ctx.moveTo(ev.clientX-canvas.offsetLeft, ev.clientY-canvas.offsetTop);
	}
	canvas.onmouseup = function () {
		isPress = false;
	}
	canvas.onmousemove = function (ev) {
		if (isPress) {
			ctx.lineTo(ev.clientX-canvas.offsetLeft, ev.clientY-canvas.offsetTop);
			ctx.stroke();
		}
	}

	function clearCanvas() {
		ctx.beginPath();
		ctx.clearRect(0, 0, 600, 600);
	}

	function exportImg() {
		var img = new Image();
		img.src = canvas.toDataURL();
		imgBox.appendChild(img);
		ctx.clearRect(0, 0, 600, 600);
		ctx.beginPath();
	}

	function clearImg() {
		imgBox.innerHTML = '';
	}
</script>